$(document).ready(function() {
	
	$.ajax({
		url : '/loadUser',
		type : 'post',
		contentType : 'application/json;charset=utf-8',
		data : {},
		timeout : 5000,
		dataType : 'json',
		success : function(data, textStatus) {
			
			if(data.code == 1){	    

				$('#li_welcome').html('Welcome ' + data.result.fullName);
			}
		},
		error : function(xhr, textStatus) {
			console.log(xhr)
			console.log(textStatus)
		}
	});
	
	var refreshResourceItems = [];
	
	$.ajax({
		url : '/resource/all',
		type : 'post',
		contentType : 'application/json;charset=utf-8',
		data : {},
		timeout : 5000,
		dataType : 'json',
		success : function(data, textStatus) {
			
			if(data.code == 1){

			    $.each(data.result.tools, function (index, resource) {
			    	
			    	var img = "";

			    	if(resource.name=='Jenkins'){
			    		
			    		img = '<img height="22" src="img/jenkins.png">&nbsp;&nbsp;';
					}else if(resource.name=='Tuleap'){
						
						img = '<img height="22" src="img/tuleap.png">&nbsp;&nbsp;';
					}else if(resource.name=='Sonarqube'){
						
						img = '<img height="22" src="img/Sonarqube.png">&nbsp;&nbsp;';
					}else if(resource.name=='Graylog'){
						
						img = '<img height="22" src="img/graylog.png">&nbsp;&nbsp;'; 
					}
			    	
			    	var button = "";
			    	if(resource.status == -1 || resource.status == 2){
			    		
			    		button = '<button type="button" class="btn btn-primary" id="btn_resource_id_' + resource.id + '">apply</button>';
			    	}else if(resource.status == -2 || resource.status == 0 || resource.status == 1){
			    		
			    		button = '<button type="button" disabled=disabled class="btn btn-primary" id="btn_resource_id_' + resource.id + '">apply</button>';
			    	}
			    	
			    	var toolUrl = "";
			    	if(resource.uri != null){
			    		
			    		if("Jenkins" == resource.name) {
			    			
			    			toolUrl = '<a id="tool_link_' +resource.id+ '" href="javascript:void(0)">' + resource.uri + '</a>';
			    		}else{

			    			toolUrl = '<a target="_blank" href="' +resource.uri+ '">' + resource.uri + '</a>';
			    		}
			    	}

			    	var trItem = $('<tr/>').append($('<td/>').html(img))
			    							.append($('<td/>').html(resource.desc))
			    							.append($('<td/>').html(resource.statusText)).append($('<td/>').html(toolUrl)).append($('<td/>').html(button))
	                
			        $("#table_tools").append( trItem );
			    	
			    	//保留需要刷新IP 的元素
			        if(resource.name == 'Jenkins' && resource.status == 0) {
			        	
			        	var item = {};
			        	item.id = resource.id;
			        	item.value=trItem;
			        	
			        	refreshResourceItems.push(item);
			        }
			        
	        		if("Jenkins" == resource.name) {
	        			
	        			jenkins_click( resource );
	        		}
			        
			        //apply resource
			        $('#btn_resource_id_' + resource.id).click(function(){
			        	
			        	var temp = this;

			        	var params = {};
			        	params['id'] = resource.id;
			        	params['name'] = resource.name;
			    		$.ajax({
			    			url : '/resource/apply',
			    			type : 'post',
			    			contentType : 'application/json;charset=utf-8',
			    			data : JSON.stringify(params),
			    			timeout : 5000,
			    			dataType : 'json',
			    			success : function(data, textStatus) {
			    				
			    				if(data.code == 1){
						        	$(temp).parent().parent().find('td').eq(2).html(data.result.statusText);
						        	$(temp).parent().parent().find('td').eq(3).html('<a target="_blank" href="' + data.result.uri + '">' + data.result.uri + '</a>');
						        	$('#btn_resource_id_' + resource.id).attr("disabled","disabled");
			    					
			    				}else{
			    					
			    					$(temp).parent().parent().find('td').eq(2).html('<strong>'+data.message+'</strong>');
			    				}

			    			},
			    			error : function(xhr, textStatus) {
			    				console.log(xhr)
			    				console.log(textStatus)
			    			}
			    		})
			        });
			    });
			    
			    $.each(data.result.vm, function (index, resource) {

			    	var trItem = $('<tr/>').append($('<td/>').html(resource.name)).append($('<td/>').html(resource.uri)).append($('<td/>').html(resource.statusText))
			    	
			        $("#table_vms").append( trItem );
			        
			        //保留需要刷新IP 的元素
			        if(resource.name == 'DevOps Master' && resource.status == 0) {
			        	
			        	var item = {};
			        	item.id = resource.id;
			        	item.value=trItem;
			        	refreshResourceItems.push(item);
			        }			        
			    });
				
			}
		},
		error : function(xhr, textStatus) {
			console.log(xhr)
			console.log(textStatus)
		}
	});

	var get_ip_timer = setInterval(
    		
    		function(){
    			
    			var data = [];
		        $.each(refreshResourceItems, function (index, item) {
		        	data.push(item.id);
		        });
	        	
    			$.ajax({
    				url : '/resource/refresh',
    				type : 'post',
    				contentType : 'application/json;charset=utf-8',
    				data : JSON.stringify(data),
    				timeout : 10000,
    				dataType : 'json',
    				success : function(data, textStatus) {
    					
    					if(data.code == 1){

    						$.each(data.result.tools, function (index, resource) {
    							
    					        $.each(refreshResourceItems, function (index, item) {
    					        	if(item.id == resource.id){
    					        		
    					        		item.value.find('td').eq(2).html(resource.statusText);
    					        		var toolUrl = "";
    						    		if("Jenkins" == resource.name) {
    						    			
    						    			toolUrl = '<a id="tool_link_' +resource.id+ '" href="javascript:void(0)">' + resource.uri + '</a>';
    						    		}else{

    						    			toolUrl = '<a target="_blank" href="' +resource.uri+ '">' + resource.uri + '</a>';
    						    		}
    					        		
    					        		item.value.find('td').eq(3).html(toolUrl);

    					        		if("Jenkins" == resource.name) {
    					        			
    					        			jenkins_click( resource );
    					        		}
    					        	}
    					        });
    						});
    			        	
    			        	$.each(data.result.vm, function (index, resource) {
    					        $.each(refreshResourceItems, function (index, item) {
    					        	if(item.id == resource.id){
    					        		
    					        		item.value.find('td').eq(1).html('<a>' + resource.uri + '</a>');
    					        		item.value.find('td').eq(2).html(resource.statusText);
    					        	}
    					        });
    			        	});
    			        	
    						clearInterval(get_ip_timer);
    					}
    				},
    				error : function(xhr, textStatus) {
    					console.log(xhr)
    					console.log(textStatus)
    				}
    			})
    		} ,20000
    );
	
	$('#tab_projects').on('click', function() {
		var data = {};

		$.ajax({
			url : '/project/list',
			type : 'post',
			contentType : 'application/json;charset=utf-8',
			data : JSON.stringify(data),
			timeout : 10000,
			dataType : 'json',
			success : function(data, textStatus) {
				
				if(data.code == 1){

					$("#ul_project_list li:gt(0)").remove();
					
					var index_project;
					$.each(data.result, function (index, project) {
				        
				        if(index == 0){
				        	index_project = 'li_project_' + project.id;
				        }
				        
				        refresh_projects( project );
					});
					
					$('#' + index_project).click();

				}else{

				}

			},
			error : function(xhr, textStatus) {
				console.log(xhr)
				console.log(textStatus)
			}
		})
	});	
	
	
	$('#btn_logout').on('click', function() {
		
		$.ajax({
			url : '/logout',
			type : 'get',
			contentType : 'application/json;charset=utf-8',
			data : {},
			timeout : 10000,
			dataType : 'json',
			success : function(data, textStatus) {

				if(data.code == 1){
					
					window.location.href="/login.html";
				}
			},
			error : function(data, textStatus) {
				console.log(xhr)
				console.log(textStatus)
			}
		})
	});
	
	$('#btn_add_project_view').on('click', function() {

		$('#frm_new_project input').val('');
		$('#frm_new_project textarea').val('');
		$('#btn_new_project').removeAttr("disabled");
	});
	
	$('#btn_new_project').on('click', function() {
		
		$('#btn_new_project').attr("disabled","disabled");
		var data = {};
		$('#frm_new_project input[name]').each(function() {
			data[this.getAttribute('name')] = this.value;

		});
		$('#frm_new_project textarea[name]').each(function() {
			data[this.getAttribute('name')] = this.value;
						
		});

		$.ajax({
			url : '/project/new',
			type : 'post',
			contentType : 'application/json;charset=utf-8',
			data : JSON.stringify(data),
			timeout : 60000,
			dataType : 'json',
			success : function(data, textStatus) {

				if(data.code == 1){
		        
					refresh_projects(data.result);
			        
			        $('#btn_close_new_project').click();
			        $('#li_project_' + data.result.id).click();
				}else{
					
					$("#new_project_message b").empty();
					$('#new_project_message b').append(data.message);
				}

				$('#btn_new_project').removeAttr("disabled"); 
			},
			error : function(data, textStatus) {
				console.log(xhr);
				console.log(textStatus);
				$('#btn_new_project').removeAttr("disabled"); 
			}
		})
	});
	
	$('#btn_new_pipeline_view').on('click', function() {

		$('#frm_new_pipeline input[name]').each(function() {
			if('projectId' != this.getAttribute('name')){
			
				this.value = '';
			}
			
			
		});
		$('#frm_new_pipeline textarea').val('');
		$("#templates").val('Blank');
		$('#btn_new_pipeline').removeAttr("disabled");
	});
	
	$('#btn_new_pipeline').on('click', function() {
		
		$('#btn_new_pipeline').attr("disabled","disabled");
		var data = {};
		$('#frm_new_pipeline input[name]').each(function() {
			data[this.getAttribute('name')] = this.value;
		});
		$('#frm_new_pipeline textarea[name]').each(function() {
			data[this.getAttribute('name')] = this.value;
						
		});
		
		data['template'] = $("#templates").find("option:selected").val();

		$.ajax({
			url : '/pipeline/new',
			type : 'post',
			contentType : 'application/json;charset=utf-8',
			data : JSON.stringify(data),
			timeout : 60000,
			dataType : 'json',
			success : function(data, textStatus) {

				if(data.code == 1){
		        
					refresh_pipelines(data.result);
			        
			        $('#btn_close_new_pipeline').click();
				}else{
					
					$("#new_pipeline_message b").empty();
					$('#new_pipeline_message b').append(data.message);
				}
				
				$('#btn_new_pipeline').removeAttr("disabled"); 

			},
			error : function(data, textStatus) {
				console.log(xhr);
				console.log(textStatus);
				$('#btn_new_pipeline').removeAttr("disabled"); 
			}
		})
	});	
	
	function refresh_projects( project ) {

		//添加project 菜单列表
		var li_item = $('<li id="li_project_'+ project.id +'"/>').html('<a>' + project.name + '</a>');
        $("#ul_project_list").append( li_item );
        
        //绑定click 事件
        $('#li_project_' + project.id).click(function(){
       	 
	       	 $('#ul_project_list li[class=active]').each(function(){
	       		 $(this).removeClass("active");
	       	 });
	       	 
	       	 $(this).addClass("active");
	       	 
	       	 $('#project_name').html(project.name);
	       	 $('#project_short_name').html(project.shortName);
	       	 $("#table_pipelines tbody tr").remove();
	       	 
	       	 //设置projectId 到 new pipeline节点
	       	$('#pipeline_project_id').val( project.id );
	       	
	       	var data = {};
	       	data['id'] = project.id;
			$.ajax({
				url : '/project/load',
				type : 'post',
				contentType : 'application/json;charset=utf-8',
				data : JSON.stringify(data),
				timeout : 5000,
				dataType : 'json',
				success : function(data, textStatus) {
					
					if(data.code == 1){
					    $.each(data.result.pipelines, function (index, pipeline) {
					    	
					    	refresh_pipelines(pipeline);
						});
					}else{

					}

				},
				error : function(xhr, textStatus) {
					console.log(xhr)
					console.log(textStatus)
				}
			})	       	
	       	
	       	
	       	
       });
	}
	
	function refresh_pipelines( pipeline ) {
//		var pipeline_name = '<a id=pipeline_link_"' +pipeline.id+ '" href="javascript:void(0)">' + pipeline.name + '</a>';
		var pipeline_name = '<a target="_blank" href="' +pipeline.url+ '">' + pipeline.name + '</a>';
        $("#table_pipelines").append(
        		$('<tr/>') 
                .append($('<td/>').html(pipeline_name))
                .append($('<td/>').html(pipeline.template))
                .append($('<td/>').html(pipeline.gitRepo))
                .append($('<td/>').html(pipeline.gitBranch))
        );
        
//        var context_index = pipeline.url.indexOf('8080') + 4;
//        var login = pipeline.url.substr(0, context_index);
//        var uri = pipeline.url.substr(context_index);
//        alert(login);
//        alert(uri);
		//for test...
//        $('#pipeline_link_' + pipeline.id).click(function(){
//        	
//    		var inputs = [];  
//    		inputs.push($('<input>', {name: 'j_username', value: 'admin'}));  
//    		inputs.push($('<input>', {name: 'j_password', value: 'admin'}));
//
//    		var form = $('<form />', {  
//    		    method: 'post',  
//    		    action: login + '/j_acegi_security_check?from=/blue/organizations/jenkins/devops_aas_demo3/activity',
//    		    target: '_blank'
//    		}).appendTo('body');
//    		form.append(inputs)
//    		form.submit();
//    		form.remove();
//        });
	}
	
	function jenkins_click( resource ){
		
        $('#tool_link_' + resource.id).click(function(){
        	
    		var inputs = [];  
    		inputs.push($('<input>', {name: 'j_username', value: 'admin'}));  
    		inputs.push($('<input>', {name: 'j_password', value: 'admin'}));

    		var form = $('<form />', {  
    		    method: 'post',  
    		    action: resource.uri + '/j_acegi_security_check',
    		    target: '_blank'
    		}).appendTo('body');
    		form.append(inputs)
    		form.submit();
    		form.remove();
        });
	}
});